package com.example.demovote.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demovote.entity.User;
import com.example.demovote.mapper.UserMapper;
import com.example.demovote.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demovote.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 投票系统-用户表-4 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;
    @Override
    public Result login(String name, String pwd) {
        // 判断用户的输入
        if(name == null || name.trim().isEmpty()){
            return new Result(0, "请输入用户名", null);
        }
        if(pwd == null || pwd.trim().isEmpty()){
            return new Result(-1, "请输入密码", null);
        }
        // 执行查询
        User user = userMapper.selectForLogin(name, pwd);
        // 判断结果
        if(user==null){
            return new Result(-2, "用户名或密码错误！", null);
        }
        // 返回结果
        return new Result(1, "登录成功！", user);
    }

    @Override
    public Result register(User user, String repwd) {
        // 判断用户的输入
        if(user.getUname() == null || user.getUname().trim().isEmpty()){
            return new Result(0, "请输入用户名", null);
        }
        if(user.getPwd() == null || user.getPwd().trim().isEmpty()){
            return new Result(-1, "请输入密码", null);
        }
        if(user.getPwd().length() < 6){
            return new Result(-2, "密码 chang du bu zu 6 wei", null);
        }
        if(user.getPwd().equals(repwd) == false){
            return new Result(-3, "que ren 密码 bu zheng que", null);
        }

        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        // uname = ?
        qw.eq(User::getUname, user.getUname());
        Long count = userMapper.selectCount(qw);
        if(count>0){
            return new Result(-4, "the user alreay register!", null);
        }
        userMapper.insert(user);
        return new Result(1, "user register success!", user);
    }

}
